package com.lj.demo.springbootshirojwt.exception;

import com.lj.demo.springbootshirojwt.entity.ResponseResult;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Title: 全局异常处理类
 * Description:
 * Date: 2019年06月26日 10:21
 *
 * @author lvjie@hiynn.com
 * @version 1.0
 * Significant Modify：
 * Date                  Author                 Content
 * =================================================================
 * 2019年06月26日         lvjie@hiynn.com         创建文件,实现基本功能
 * =================================================================
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义权限异常
     * @param e
     * @return
     */
    @ExceptionHandler({AuthorizationException.class})
    public ResponseResult globalAuthorizationExceptionHandler(Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 处理shiro异常
     * @param e
     * @return
     */
    @ExceptionHandler({ShiroException.class})
    public ResponseResult globalShiroExceptionHandler(Exception e) {
        String message = e.getMessage();
        LOGGER.error(e.getMessage(), e);
        if (e instanceof UnknownAccountException){
            message = "用户不存在";
        }
        if (e instanceof IncorrectCredentialsException){
            message = "用户名无效";
        }
        if (e instanceof AuthenticationException){
            message = "密码错误";
        }
        if (e instanceof UnauthorizedException){
            message = "权限不足";
        }
        if (e instanceof UnauthenticatedException){
            message = "token不合法";
        }
        return ResponseResult.fail(message);
    }

    /**
     * 处理全部异常
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ResponseResult globalExceptionHandler(Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseResult.fail(e.getMessage());
    }
}
